package com.common.servlet;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.common.utils.SysConfig;

/**
 * @说明 该Servlet将本地硬盘的图片输入管道中
 * @author cuisuqiang
 * @version 1.0
 * @since
 */
@SuppressWarnings("serial")
public class ImageShowServlet extends HttpServlet {

	  // 定义文件的上传路径 
    private String uploadPath ; 
    
	@Override
	protected void service(HttpServletRequest request,
			HttpServletResponse response) throws ServletException {
		 uploadPath = SysConfig.imgRealPath;
		 String imgName = request.getParameter("imgName");
		OutputStream os = null;
		FileInputStream fips =null;
		try {
			File filePath = new File(uploadPath);
			if(!filePath.isDirectory()){
				filePath.mkdirs();
			}
			
			os = response.getOutputStream();
			File file = new File(uploadPath+imgName);
			 fips = new FileInputStream(file);
			byte[] btImg = readStream(fips);
			os.write(btImg);
			os.flush();
		} catch (IOException e) {
			e.printStackTrace();
		}finally{
			if(os!=null){
				try {
					os.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if(fips!=null){
				try {
					fips.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		
	}

	/**
	 * 读取管道中的流数据
	 */
	public byte[] readStream(InputStream inStream) {
		ByteArrayOutputStream bops = new ByteArrayOutputStream();
		int data = -1;
		try {
			while ((data = inStream.read()) != -1) {
				bops.write(data);
			}
			return bops.toByteArray();
		} catch (Exception e) {
			return null;
		}
	}
}